import { FC, useEffect, useState } from "react";
import { NonIndexRouteObject, useRoutes } from "react-router";
import { useRecoilState } from "recoil";

import Page404 from "../pages/404/index";
import IndexPage from "../pages/index";
import { userState } from "../stores/user";
import WapperRoutComponent from "./config";
import LoginPage from "../pages/login";
import { RouteVO } from "../service/rbac/menu-service";
import MonitorPage from "../pages/index/monitor";
import WorkPlacePage from "../pages/index/workplace";
import DashboardPage from "../pages/index/home";
import SysPage from "../pages/index/sys";
import SysRolePage from "../pages/index/sys-role";
import UnitPage from "../pages/index/unit";
import BeefTypePage from "../pages/index/beef-type";
import ArticlePage from "../pages/index/article";
import LawTypePage from "../pages/index/laws-type";
import LawPage from "../pages/index/laws";
import BeefPage from "../pages/index/beef";
import IndexDashboardPage from "../pages/index/dashboard";
import JdUnitPage from "../pages/index/jd-unit";

export type RouterType = {
  text?: string;
  children?: RouterType[];
} & Omit<NonIndexRouteObject, "children">;

//路由地址对应的映射
export const defaultRouteVO: RouterType[] = [
  {
    path: "/backweb/workplace",
    element: <WorkPlacePage />,
  },
  {
    path: "/backweb/home",
    element: <DashboardPage />,
  },
  {
    path: "/backweb/monitor",
    element: <MonitorPage />,
  },

  {
    path: "/backweb/system/sys",
    element: <SysPage />,
  },
  {
    path: "/backweb/system/sys-role",
    element: <SysRolePage />,
  },
  {
    path: "/backweb/system/unit",
    element: <UnitPage />,
  },
  {
    path: "/backweb/beeftype",
    element: <BeefTypePage />,
  },
  {
    path: "/backweb/article",
    element: <ArticlePage />,
  },
  {
    path: "/backweb/lawstype",
    element: <LawTypePage />,
  },
  {
    path: "/backweb/laws",
    element: <LawPage />,
  },
  {
    path: "/backweb/jdunit",
    element: <JdUnitPage />,
  },
  {
    path: "/backweb/beef",
    element: <BeefPage />,
  },
  {
    path: "/backweb/dashboard",
    element: <IndexDashboardPage />
  }
];

/**
 * 初始化的路由
 */
export const defaultRoute = [
  {
    path: "/",
    element: (
      <WapperRoutComponent auth={true}>
        <IndexPage />
      </WapperRoutComponent>
    ),
  },
  {
    path: "login",
    element: <LoginPage />,
  },
];

/**
 * 获取到路径对应的组件
 * @param path 路径
 * @returns 组件
 */
const getElementRouteNode = (path: string): React.ReactNode => {
  return defaultRouteVO.filter((element) => element.path === path)[0].element;
};

/**
 * 递归过滤权限, 动态加上 Navigate 跳转
 * @param parentId  上级路由ID
 * @param routes 路由映射地址
 * @returns  route组件
 */
export const filterPermissions = (
  parentId: number,
  routes?: RouteVO[]
): RouterType[] => {
  const children: RouterType[] = [];
  routes?.forEach((route) => {
    if (route.parentId === parentId) {
      const node = getElementRouteNode(route.path);
      if (node) {
        //检查是否有子路由
        const childRoutes = routes.filter((e) => e.parentId === route.id);
        const routeData: RouterType = {
          path: route.path,
          element: node,
          text: route.meta.title,
        };

        if (childRoutes.length > 0) {
          routeData.children = filterPermissions(route.id, routes);
        }
        children.push(routeData);
      }
    }
  });
  return children;
};

const RenderRouter: FC = () => {
  const [user] = useRecoilState(userState);
  const [routerState, setRouteState] = useState<RouterType[]>(defaultRoute);
  useEffect(() => {
    if (user && user.token) {
      //默认第一级路由parentId === 0;
      const children = filterPermissions(0, user.route);
      setRouteState([
        {
          path: "/",
          element: (
            <WapperRoutComponent auth={true}>
              <IndexPage />
            </WapperRoutComponent>
          ),
          children: children,
        },
        {
          path: "login",
          element: <LoginPage />,
        },
        {
          path: "*",
          element: <Page404 />,
        },
      ]);
    }
  }, [user]);
  //过滤权限
  return useRoutes(routerState);
};

export default RenderRouter;
